<template>
  <div class="debug-page">
    <el-card>
      <div slot="header">
        <h2>区块链连接诊断</h2>
      </div>
      
      <el-alert
        title="使用说明"
        type="info"
        description="点击下面的按钮检测 MetaMask 连接状态、网络配置和智能合约部署情况"
        :closable="false"
        style="margin-bottom: 20px;"
      >
      </el-alert>
      
      <el-button @click="runDiagnostics" type="primary" :loading="loading">
        运行诊断
      </el-button>
      
      <div style="margin-top: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
        <p style="margin: 0 0 8px 0; font-weight: bold;">🔍 快速检查（在浏览器控制台 F12 运行）：</p>
        <code style="background: #fff; padding: 5px 10px; border-radius: 3px; display: inline-block;">
          typeof window.ethereum
        </code>
        <p style="margin: 8px 0 0 0; font-size: 12px; color: #606266;">
          • 如果返回 "undefined"，说明 MetaMask 未安装<br>
          • 如果返回 "object"，说明 MetaMask 已安装
        </p>
      </div>
      
      <div v-if="results" class="results">
        <h3>诊断结果</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="钱包已连接">
            <el-tag :type="results.walletConnected ? 'success' : 'danger'">
              {{ results.walletConnected ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前账户">
            {{ results.account || '未连接' }}
          </el-descriptions-item>
          <el-descriptions-item label="当前网络">
            {{ results.network }}
          </el-descriptions-item>
          <el-descriptions-item label="Chain ID">
            {{ results.chainId }}
          </el-descriptions-item>
          <el-descriptions-item label="账户余额">
            {{ results.balance }} ETH
          </el-descriptions-item>
          <el-descriptions-item label="合约地址">
            {{ results.contractAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="合约已部署">
            <el-tag :type="results.contractDeployed ? 'success' : 'danger'">
              {{ results.contractDeployed ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="results.error" class="error-section">
          <h4>错误信息：</h4>
          <pre>{{ results.error }}</pre>
        </div>
        
        <div class="recommendations">
          <h4>建议：</h4>
          <ul>
            <li v-if="!results.walletConnected">
              ❌ 请先连接 MetaMask 钱包
            </li>
            <li v-if="results.chainId !== '31337'">
              ❌ 请在 MetaMask 中切换到 Hardhat Local 网络（Chain ID: 31337）
            </li>
            <li v-if="!results.contractDeployed">
              ❌ 合约未部署或地址错误，请重新部署合约
            </li>
            <li v-if="parseFloat(results.balance) < 0.1">
              ⚠️ 账户余额不足，可能影响交易
            </li>
            <li v-if="results.walletConnected && results.chainId === '31337' && results.contractDeployed">
              ✅ 配置正确！如果创建众筹仍失败，请检查表单输入
            </li>
          </ul>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import web3Helper from '@/utils/web3';
import contractService from '@/api/contract';

export default {
  name: 'Debug',
  data() {
    return {
      loading: false,
      results: null
    };
  },
  methods: {
    async runDiagnostics() {
      this.loading = true;
      const results = {
        walletConnected: false,
        account: null,
        network: null,
        chainId: null,
        balance: '0',
        contractAddress: null,
        contractDeployed: false,
        error: null
      };
      
      try {
        // 首先检查 window.ethereum 是否存在
        if (typeof window.ethereum === 'undefined') {
          results.error = 'MetaMask 未安装或未启用！请安装 MetaMask 浏览器扩展。';
          this.results = results;
          this.loading = false;
          return;
        }
        
        // 检查钱包连接
        const account = web3Helper.getAccount();
        results.walletConnected = !!account;
        results.account = account;
        
        if (account) {
          // 获取网络信息
          const network = await web3Helper.getNetwork();
          results.network = network.name;
          results.chainId = network.chainId.toString();
          
          // 获取余额
          results.balance = await web3Helper.getBalance(account);
          
          // 检查合约
          await contractService.init();
          const contractInfo = contractService.contractInfo;
          results.contractAddress = contractInfo.address;
          
          // 尝试调用合约的只读方法
          const contract = contractService.getContract();
          const count = await contract.count();
          results.contractDeployed = true;
          results.campaignCount = count.toNumber();
        }
      } catch (error) {
        results.error = error.message;
        console.error('诊断失败:', error);
      } finally {
        this.loading = false;
        this.results = results;
      }
    }
  }
};
</script>

<style scoped>
.debug-page {
  max-width: 800px;
  margin: 50px auto;
  padding: 20px;
}

.results {
  margin-top: 30px;
}

.error-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
  border-radius: 4px;
}

.error-section pre {
  margin: 10px 0 0 0;
  color: #f56c6c;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.recommendations {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9ff;
  border: 1px solid #d1e9ff;
  border-radius: 4px;
}

.recommendations ul {
  margin: 10px 0 0 0;
  padding-left: 20px;
}

.recommendations li {
  margin: 8px 0;
  line-height: 1.6;
}
</style>

